package com.zx.cloud.lisenter;

import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.quartz.Trigger.CompletedExecutionInstruction;
import org.quartz.TriggerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.zx.cloud.common.filter.limit.LimiterStatsService;
import com.zx.cloud.common.filter.limit.LimiterStatsService.LimiterCallback;
import com.zx.cloud.common.filter.limit.LimiterStatsService.LimiterContext;
import com.zx.cloud.domain.ScheduleJob;
import com.zx.cloud.job.TaskUtils;

@Component("daemonTriggerListener")
public class DaemonTriggerListener implements TriggerListener {

	private static final Logger logger = LoggerFactory.getLogger(DaemonTriggerListener.class);

	@Override
	public String getName() {
		return "DaemonTriggerListener";
	}

	@Override
	public void triggerFired(Trigger trigger, JobExecutionContext context) {
		logger.debug("启动队列[{}]中[{}]任务.", trigger.getKey().getGroup(), trigger.getKey().getName());
	}

	@Override
	public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {
		logger.debug("触发器[" + trigger.getKey().getGroup() + "],[" + trigger.getKey().getName() + "]被激活！！！");
		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
		String key = scheduleJob.getJobGroup()+scheduleJob.getJobName();
		LimiterStatsService.getInstance().execute(key, 1,3, new LimiterCallback() {

			@Override
			public void noexecute(LimiterContext limiterContext) {
			}

			@Override
			public void execute(LimiterContext limiterContext) {
				TaskUtils.invokMethod(scheduleJob);
			}
		});
		return true;
	}

	@Override
	public void triggerMisfired(Trigger trigger) {
		logger.warn("队列[" + trigger.getKey().getGroup() + "]中[" + trigger.getKey().getName() + "]任务错过执行");
	}

	@Override
	public void triggerComplete(Trigger trigger, JobExecutionContext context, CompletedExecutionInstruction triggerInstructionCode) {
		logger.debug("完成队列[{}]中[{}]任务.", trigger.getKey().getGroup(), trigger.getKey().getName());
	}

}
